<template>
	<dv-border-box-1>
		<div id="three" ref="three">
		</div>
	</dv-border-box-1>
</template>

<script>
	import * as THREE from "three"
	import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader.js';
	import { MTLLoader } from 'three/examples/jsm/loaders/MTLLoader.js'
	import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js"
	export default{
		props:{
			materialurl:String,
			modelurl:String,
			scale:Number
		},
		data() {
			return{
				three:""
			}
		},
		watch:{
			materialurl(){
				var obj =document.getElementById("three");
				var parent = obj.parentNode;
				obj.parentNode.removeChild(obj);
				parent.innerHTML ="<div id='three' ref='three' style='height:100%;width:100%'> </div>"
				this.init3d();
			}
		},
		mounted() {
			this.init3d();
			this.render();
			window.addEventListener('resize',()=>{
				this.logoBoxResize();
			})
		},
		methods:{
			init3d(){
				this.three = document.getElementById("three")
				this.camera = new THREE.PerspectiveCamera(45,this.three.offsetWidth/this.three.offsetHeight,0.1,200);
				this.camera.position.set(0,0,15);
				// 实例化场景
				this.scene = new THREE.Scene();
				// 添加环境光
				const aLight = new THREE.AmbientLight(0xffffff);
				aLight.intensity = 2;
				this.scene.add(aLight);
				// 创建渲染器
				this.renderer = new THREE.WebGLRenderer({
					alpha: true
				});
				
				this.renderer.setSize(this.three.offsetWidth,this.three.offsetHeight);
				this.three.appendChild(this.renderer.domElement);
				const controls = new OrbitControls(this.camera,this.renderer.domElement);
				// objLoader
				var objLoader = new OBJLoader();
				var mtlLoader = new MTLLoader();
				// 坐标
				var axis = new THREE.AxisHelper(20);
				// 加载Obj模型
				mtlLoader.load(this.materialurl,(materials)=>{
					objLoader.setMaterials(materials);
					objLoader.load(this.modelurl,(res)=>{
						let obj = res
						obj.scale.set(this.scale,this.scale,this.scale);
						obj.position.set(0,0,0)
						this.scene.add(obj)
					})
				})
				
				this.renderer.render(this.scene, this.camera);
			},
			render(){
				var axisNato = new THREE.Vector3(0,1,0);
				var natoLogo = this.scene.children[1]
				requestAnimationFrame(this.render);
				if(natoLogo == undefined){
					return
				}
				natoLogo.rotateOnAxis(axisNato,0.01)
				this.renderer.render(this.scene, this.camera);
			},
			logoBoxResize(){
				this.renderer.setSize(this.three.offsetWidth,this.three.offsetHeight);
				this.camera.aspect = this.three.offsetWidth/this.three.offsetHeight ;
				this.camera.updateProjectionMatrix();
			}
		},
	}
</script>

<style scoped="scoped">
	#three{
		height: 100%;
		width: 100%;
	}
</style>
